package main

import "fmt"

// 如何计算一个数的 n 次方

func main() {
	fmt.Println(power1(2, 3))
	fmt.Println(power1(-2, 3))
	fmt.Println(power1(2, -3))

	fmt.Println(power2(2, 3))
	fmt.Println(power2(-2, 3))
	fmt.Println(power2(2, -3))
}

// 直接法
func power1(d float64, n int) float64 {
	if n == 0 {
		return 1
	}

	if n == 1 {
		return d
	}

	result := 1.0
	if n > 0 {
		for i := 0; i < n; i++ {
			result *= d
		}
		return result
	} else {
		for i := 0; i < -n; i++ {
			result = result / d
		}

		return result
	}
}

// 递归法
func power2(d float64, n int) float64 {
	if n == 0 {
		return 1
	}
	if n == 1 {
		return d
	}

	var tmp float64

	if n > 0 {
		tmp = power2(d, n/2)
		if n%2 == 1 {
			return tmp * tmp * d
		} else {
			return tmp * tmp
		}
	} else {
		tmp = power2(d, -n/2)
		if n%2 == -1 {
			return 1 / (tmp * tmp * d)
		} else {
			return 1 / (tmp * tmp)
		}
	}
}
